import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { ILoginData, IUserInfo } from '@/api/user/types'
import { getTime } from '@/utils/times'
import { useRouter } from 'vue-router'
import { constantRoute } from '@/router/routes'
import type { RouteRecordRaw } from 'vue-router'
// import { ElNotification } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<IUserInfo>(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const token = ref<string>(localStorage.getItem('token') ? JSON.parse(localStorage.getItem('token') || '{}') : '')
  // 菜单列表
  let menuRoutes: RouteRecordRaw[] = constantRoute
  const router = useRouter()
  // 用户登录login
  const userLogin = async (loginData: ILoginData) => {
    const res = await reqLogin(loginData)
    if (res.code === 200) {
      // Object.assign(userInfo, data.result)
      token.value = res.data
      localStorage.setItem('token', JSON.stringify(res.data))
      // TS中不能使用route获取redirect的参数，无法跳回到指定页面
      // router.push((route.query.redirect as string) || '/')
      const params = new URLSearchParams(window.location.search)
      const redirect = params.get('redirect')
      router.push(redirect || '/')
      // 获取用户信息
      getUserInfo()
      ElNotification({
        type: 'success',
        title: 'Hi,' + getTime(),
        message: '欢迎回来'
      })
    } else {
      ElMessage.error('用户登录失败！')
      throw new Error('用户登录失败！' + res.message)
    }
  }
  // 用户退出 logout
  const userLogout = async () => {
    await ElMessageBox.confirm('确认用户退出吗？', '退出询问', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).catch(() => {
      ElMessage.info('已取消！')
      return new Promise(() => {})
    })
    await reqLogout().catch(() => {})
    userInfo.value = {} as IUserInfo
    token.value = ''
    menuRoutes = []
    window.localStorage.clear() // removeItem()
    ElMessage.success('用户已退出！')
    router.replace({ name: 'login' })
  }

  // 获取用户信息
  const getUserInfo = async () => {
    const res = await reqUserInfo()
    if (res.code === 200) {
      userInfo.value.name = res.data.name
      userInfo.value.avatar = res.data.avatar
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }
  }

  return { userInfo, token, menuRoutes, userLogin, userLogout, getUserInfo }
})
